"use client";

//React-Hook-Form
import { useForm } from "react-hook-form";

//Types
import { IInputsLength, IValueState } from "@/types/types";

//Utils
import {
  emailRegular,
  passwordRegular,
  nameRegular,
  surnameRegular,
  phoneNumberRegular,
} from "@/utils/regulars";

const useCustomForm = () => {
  const {
    register,
    formState: { errors, isValid },
    getValues,
    handleSubmit,
    reset,
  } = useForm<IValueState>({ mode: "onTouched" });

  const returnRegularByInputType = (inputType: keyof IInputsLength): RegExp => {
    switch (inputType) {
      case "email":
        return emailRegular;
      case "name":
        return nameRegular;
      case "surname":
        return surnameRegular;
      case "password":
        return passwordRegular;
      case "phoneNumber":
        return phoneNumberRegular;
    }
  };

  const returnMessageByInputType = (inputType: keyof IInputsLength) => {
    switch (inputType) {
      case "email":
        return "Please enter a valid email address!";
      case "password":
        return "Password must contain at least one letter and one digit, and be at least 8 characters long!";
      case "phoneNumber":
        return "Please enter a valid phone number in the format XXX-XXX-XXXX, where X is a digit!";
      default:
        return "Field should contain only letters and start with a capital letter!";
    }
  };

  const returnInputProperties = (inputType: keyof IInputsLength) => {
    const maxLengthInput: IInputsLength = {
      email: 150,
      name: 150,
      surname: 150,
      password: 120,
      phoneNumber: 20,
    };

    const minLengthInput: IInputsLength = {
      email: 5,
      name: 2,
      surname: 2,
      password: 8,
      phoneNumber: 3,
    };

    return {
      ...register(inputType, {
        required: "This field is required!",
        minLength: {
          value: minLengthInput[inputType],
          message: `Not less ${minLengthInput[inputType]} symbols`,
        },
        maxLength: {
          value: maxLengthInput[inputType],
          message: `Not more ${maxLengthInput[inputType]} symbols`,
        },
        pattern: {
          value: returnRegularByInputType(inputType),
          message: returnMessageByInputType(inputType),
        },
      }),
    };
  };

  const returnInputError = (inputType: keyof IInputsLength) =>
    errors[inputType]?.message?.toString();

  return {
    returnInputError,
    returnInputProperties,
    isValid,
    getValues,
    handleSubmit,
    reset,
    errors,
  };
};

export { useCustomForm };
